package com.zmn.uac.business.impl.oauth.login;

import com.alibaba.fastjson.JSONObject;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.uac.business.interfaces.channel.ChannelBService;
import com.zmn.uac.business.interfaces.oauth.login.MobileCaptchaLoginBService;
import com.zmn.uac.business.interfaces.user.UserInfoBService;
import com.zmn.uac.client.*;
import com.zmn.uac.common.dict.ErrorCodeDict;
import com.zmn.uac.common.dio.oauth.login.TempCodeDIO;
import com.zmn.uac.common.dio.oauth.login.UserAuthLoginDIO;
import com.zmn.uac.common.dro.oauth.login.TokenAndUserInfoDRO;
import com.zmn.uac.common.dro.oauth.login.UserAuthLoginDRO;
import com.zmn.uac.common.dro.oauth.login.UserInfoDRO;
import com.zmn.uac.common.info.UserAuthPhoneInfo;
import com.zmn.uac.common.info.mobile.MobileCaptchaUserLoginInfo;
import com.zmn.uac.util.LogAlibabaUtil;
import com.zmn.uuc.common.constant.PassConsts;
import com.zmn.uuc.common.dio.integrate.UserRegisterMobileAndLoginByUserIdDIO;
import com.zmn.uuc.common.dio.pass.UserMobileCaptchaLoginDIO;
import com.zmn.uuc.common.dro.pass.PassIdentityBaseDRO;
import com.zmn.uuc.common.dro.user.UserBaseDRO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：手机号验证码登录业务实现
 *
 * @author xujie
 * @since 2021/06/18 17:36
 */
@Slf4j
@Service
public class MobileCaptchaLoginBServiceImpl implements MobileCaptchaLoginBService {

    private static final String TAG = "手机号验证码登录业务实现";

    @Resource
    UserInfoBService userInfoBusinessService;

    @Resource
    ChannelBService channelBusinessService;

    @Resource
    UserListClient userListClient;

    @Resource
    UserLoginIntegrateClient userLoginIntegrateClient;

    @Resource
    PassLoginClient passLoginClient;

    @Resource
    TokenClient tokenClient;

    @Resource
    StaffListClient staffListClient;

    @Override
    public ResponseDTO<UserAuthLoginDRO> login(UserAuthLoginDIO dio, UserAuthPhoneInfo authPhoneInfo) {
        Integer channelId = dio.getChannelId();
        MobileCaptchaUserLoginInfo mobileCaptchaUserLoginInfo = (MobileCaptchaUserLoginInfo) authPhoneInfo;

        List<UserBaseDRO> userBaseList = userListClient.listUserByMobile(mobileCaptchaUserLoginInfo.getMobile(), Boolean.TRUE);
        Boolean newUser = CollectionUtil.isNullOrEmpty(userBaseList);
        // 获取渠道名称
        String channelName = channelBusinessService.getNameByChannelId(channelId);
        UserRegisterMobileAndLoginByUserIdDIO loginByUserId = new UserRegisterMobileAndLoginByUserIdDIO();
        loginByUserId.setPlat(dio.getPlat());
        loginByUserId.setMobile(mobileCaptchaUserLoginInfo.getMobile());
        loginByUserId.setCaptcha(mobileCaptchaUserLoginInfo.getCaptcha());
        loginByUserId.setChannelId(channelId);
        // 获取渠道名称
        loginByUserId.setChannelName(channelName);
        // 注册入口
        loginByUserId.setEntrance(dio.getEntrance());


        ResponseDTO<String> response = userLoginIntegrateClient.registerAndLoginThirdByMobile(loginByUserId);
        if (!response.isSuccess()) {
            log.error("[{}]，通过手机号和验证码注册并登录失败：{}，参数：{}", TAG, response.getMessage(), JSONObject.toJSONString(loginByUserId));
            return ResponseDTO.fail(response.getMessage());
        }
        String token = response.getData();

        ResponseDTO<UserAuthLoginDRO> authLoginResponse = userInfoBusinessService.getUserInfoByToken(token);
        if (authLoginResponse.isSuccess()) {
            authLoginResponse.getData().setNewUser(newUser);
            log.info("大数据日志打印到特定服务上 UserAuthLoginDRO={},authPhoneInfo={},loginByUserId={}",authLoginResponse.getData(),authPhoneInfo,loginByUserId);
            ResponseDTO<Long> passIdResp = userInfoBusinessService.getPassIdByToken(token);
            LogAlibabaUtil.loginLog(authLoginResponse.getData(), authPhoneInfo, loginByUserId, passIdResp.getData());
        }

        return authLoginResponse;
    }

    @Override
    public ResponseDTO<String> getOpenIdByCode(TempCodeDIO tempCodeDIO) {
        return null;
    }

    @Override
    public ResponseDTO loginByMobileCaptcha(String mobile, String captcha) {
        TokenAndUserInfoDRO userInfoDRO = new TokenAndUserInfoDRO();

        // 获取token
        UserMobileCaptchaLoginDIO userMobileCaptchaLoginDIO = setUserMobileCaptchaLoginDIO(mobile, captcha);
        ResponseDTO<String> responseDTO = passLoginClient.loginByMobileCaptchaWithResponse(userMobileCaptchaLoginDIO);
        if(!responseDTO.isSuccess()){
            log.error("[{}]，通过手机号和验证码登录失败：{}", TAG, responseDTO.getMessage());
            // 账号不存在特殊返回
            if(responseDTO.getStatus().equals(ErrorCodeDict.USER_NOT_FOUND)){
                return responseDTO;
            }else{
                return ResponseDTO.fail(responseDTO.getMessage());
            }
        }
        String token = responseDTO.getData();

        userInfoDRO.setToken(token);

        // 获取用户信息
        ResponseDTO<UserInfoDRO> userInfoResponse = this.getUserInfoByToken(token);
        if(userInfoResponse.isSuccess() && Objects.nonNull(userInfoResponse.getData())){
            userInfoDRO.setUserInfo(userInfoResponse.getData());
        }
        return ResponseDTO.success(userInfoDRO);
    }

    @Override
    public ResponseDTO<UserInfoDRO> getUserInfoByToken(String token) {
        log.info("[{}],登录token获取登录用户身份信息入参：[{}]",TAG, token);
        ResponseDTO<List<PassIdentityBaseDRO>> response = tokenClient.listPassIdentityByTokenWithResponse(token);
        if(!response.isSuccess()){
            if(response.getStatus().equals(ErrorCodeDict.LOGIN_EXPIRE_TIME) || response.getStatus().equals(ErrorCodeDict.REDIS_EXPIRE_TIME)){
                return ResponseDTO.fail(ErrorCodeDict.LOGIN_EXPIRE_GATE_WAY_TIME_OUT,response.getMessage());
            }else{
                return ResponseDTO.fail(response.getMessage());
            }
        }
        if(CollectionUtil.isNullOrEmpty(response.getData())){
            log.error("[{}]，登录token获取登录用户身份信息返回数据为空", TAG);
            return ResponseDTO.fail();
        }

        // 筛选出登录的
        PassIdentityBaseDRO hadBeenLogin = response.getData().stream().filter(item ->item.getLogined().equals(GlobalConsts.YES)).findFirst().orElse(null);

        UserInfoDRO dro = new UserInfoDRO();
        dro.setAvatarSrc(GlobalConsts.SPLITER_EMPTY);

        String realName = StringUtil.isNotBlank(hadBeenLogin.getIdentityObjectName()) ? hadBeenLogin.getIdentityObjectName(): GlobalConsts.SPLITER_EMPTY;
        String jobs = GlobalConsts.SPLITER_EMPTY;
        Long userId = Objects.nonNull(hadBeenLogin.getIdentityObjectId()) ? hadBeenLogin.getIdentityObjectId() :null;

        if(hadBeenLogin.getIdentityType().equals(PassConsts.PASS_IDENTITY_TYPE_STAFF)){
            log.info("[{}]，根据userId获取员工信息入参：{}", TAG,hadBeenLogin.getIdentityObjectId());
            StaffDRO staffDRO = staffListClient.getStaff(hadBeenLogin.getIdentityObjectId().intValue());
            // 用户ID
            userId = Long.valueOf(staffDRO.getStaffId());
            // 用户姓名
            realName = staffDRO.getRealName();
            // 职位
            if(StringUtil.isNotBlank(staffDRO.getPost()) || StringUtil.isNotBlank(staffDRO.getDeptName())){
                jobs =  StringUtil.isNotBlank(staffDRO.getPost()) ? staffDRO.getPost() : staffDRO.getDeptName();
            }

            //公司名称
            if (staffDRO.getCompanyId() != null) {
                CompanyDRO company = staffListClient.getCompany(staffDRO.getCompanyId());
                dro.setCompanyId(staffDRO.getCompanyId());
                dro.setCompanyName(company.getName());
            }

            dro.setDepId(staffDRO.getDeptId());
            dro.setDepName(staffDRO.getDeptName());
        }

        // 用户ID
        dro.setUserId(userId);
        // 用户姓名
        dro.setRealName(realName);
        // 职位
        dro.setJob(jobs);

        return ResponseDTO.success(dro);
    }



    @Override
    public ResponseDTO<Boolean> logout(String token) {
        Boolean result = passLoginClient.logout(token);

        return ResponseDTO.success(result);
    }

    private UserMobileCaptchaLoginDIO setUserMobileCaptchaLoginDIO(String mobile, String captcha){
        UserMobileCaptchaLoginDIO userMobileCaptchaLoginDIO = new UserMobileCaptchaLoginDIO();
        // 平台标识
        userMobileCaptchaLoginDIO.setPlat(GlobalConsts.PLAT_MARK_ZMN);
        // 身份类型
        userMobileCaptchaLoginDIO.setIdentityType(PassConsts.PASS_IDENTITY_TYPE_STAFF);
        // 手机号
        userMobileCaptchaLoginDIO.setMobile(mobile);

        // 验证码
        userMobileCaptchaLoginDIO.setCaptcha(captcha);

        return userMobileCaptchaLoginDIO;
    }
}
